package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @作者 itcast
 * @创建日期 2020/10/7 14:47
 **/
@Service
@Transactional
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDto dto) {
        // 1.参数校验
        if(dto.getEquipmentId() == null && (StringUtils.isEmpty(dto.getPhone()) && StringUtils.isEmpty(dto.getPassword()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(!StringUtils.isEmpty(dto.getPhone())&&!StringUtils.isEmpty(dto.getPassword())){
            // 用户名密码登录
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if(apUser!=null){
                // 判断密码是否正确
                String inputPswd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
                if(apUser.getPassword().equals(inputPswd)){
                    Map<String,Object> map = new HashMap();
                    apUser.setPassword("");
                    apUser.setSalt("");
                    map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                    map.put("user",apUser);
                    return ResponseResult.okResult(map);
                }else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
        }else {
            // 根据设备号登录
            if(dto.getEquipmentId() == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            Map<String,Object> map = new HashMap();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }

//    public static void main(String[] args) {
//        String s = DigestUtils.md5DigestAsHex("admin123abc".getBytes());
//        System.out.println(s);
//    }
}
